<script lang="ts" setup>
import { reactive, ref, onActivated, onMounted } from 'vue'
import { feeRulesType } from '@/types/interface'
import { useRoute, useRouter } from 'vue-router'
import { queryBikeShortTermProduct } from '@/api/store'
import {
  queryBikeShortTermProductRequestData,
  BikeShortTermProductType
} from '@/api/store/types/store'
import { returnLocationType } from '@/types/interface'
import { useActivated } from '@/hooks/useActivated'
import { getToken } from '@/utils/cache/cookies'
import { useMap } from '@/hooks/useMap'
import returnPointImg from '@/assets/map/timeRentConfigure/returnPoint.png'
import activeReturnPointImg from '@/assets/map/timeRentConfigure/activeReturnPoint.png'
import { ElMessage } from 'element-plus'
import { FeeRulesType } from '@/types/enum'

defineOptions({
  name: 'TimeRentConfigure'
})
const route = useRoute()
const form = reactive<queryBikeShortTermProductRequestData>({
  storeId: route.query.storeId as string
})
const dispatchFee = ref<string>('0')
interface returnLocationMapType extends returnLocationType {
  lnglat: [number, number]
}
const returnLocation = ref<returnLocationMapType[]>([])
const product = ref<BikeShortTermProductType[]>([])
const feeRuleDetail = ref<feeRulesType[]>([])
const getData = async () => {
  try {
    returnLocation.value = []
    massmarks.value?.clear()
    const res = await queryBikeShortTermProduct({
      storeId: form.storeId,
      token: getToken() ?? ''
    })
    if (res.statusCode === '0') {
      const firstProduct = res.data.product[0]
      product.value = res.data.product
      feeRuleDetail.value = res.data.feeRuleDetail
      dispatchFee.value = firstProduct.dispatchFee
      returnLocation.value = handleReturnLocation(res.data.returnLocation)
      handleCoverInit()
    }
  } catch (error) {
    console.error(error)
  }
}
const handleReturnLocation = (data: returnLocationType[]) => {
  return data.map((location: returnLocationType) => {
    return {
      lnglat: [location.longtitude, location.latitude] as [number, number],
      ...location
    }
  })
}
const isInit = ref<boolean>(false)
const mapContainer = ref<HTMLDivElement>()
const massmarks = ref<AMap.MassMarks>()
const infowindow = ref<AMap.InfoWindow>()
const circle = ref<AMap.Circle>()
const center = reactive({
  longtitude: 0,
  latitude: 0
})
const { map, initAmap, geocoder } = useMap(mapContainer, [center.longtitude, center.latitude])
const getStyle = () => {
  return [
    {
      anchor: new AMap.Pixel(0, 0),
      url: returnPointImg,
      size: new AMap.Size(30, 30)
    },
    {
      anchor: new AMap.Pixel(0, 0),
      url: activeReturnPointImg,
      size: new AMap.Size(30, 30)
    }
  ]
}
const init = async () => {
  isInit.value = await initAmap()
  await getData()
}

const createContent = (address: string, returnLocationsId: number, title: string) => {
  return `<div class="return-point-infowindow">
                  <div class="return-point-infowindow__title">
                    <span class="return-point-infowindow__name">${title}</span>
                    <div class="return-point-infowindow__id-content">
                        <span>编号:${returnLocationsId}</span>
                    </div>
                  </div>
                  <div class="return-point-infowindow__address">
                    <span>${address}</span>
                  </div>
              </div>`
}
const handleMassMarksClick = (e: any) => {
  const index = returnLocation.value.findIndex(
    (item) => item.lnglat[1] === e.data.latitude && item.lnglat[0] === e.data.longtitude
  )
  circle.value?.setCenter(e.data.lnglat)
  circle.value?.setRadius(e.data.radius)
  if (infowindow.value?.getIsOpen()) {
    infowindow.value.close()
    returnLocation.value = returnLocation.value.map((item) => {
      return {
        ...item,
        style: 0
      }
    })
    massmarks.value?.setData(returnLocation.value)
    circle.value?.hide()
  } else {
    returnLocation.value = returnLocation.value.map((item, i) => {
      if (index == i) {
        return {
          ...item,
          style: 1
        }
      } else {
        return {
          ...item,
          style: 0
        }
      }
    })
    massmarks.value?.setData(returnLocation.value)
    geocoder.value.getAddress(e.data.lnglat, (status: any, result: any) => {
      if (result.info == 'OK') {
        const name = result.regeocode.aois
          ? result.regeocode.aois[0].name
          : result.regeocode.formattedAddress
        infowindow.value?.setContent(createContent(e.data.address, e.data.returnLocationsId, name))
      } else {
        // 处理获取地址失败的情况
        ElMessage.error('地址解析失败')
        infowindow.value?.setContent(createContent(e.data.address, e.data.returnLocationsId, ''))
      }
      circle.value?.show()
      infowindow.value?.open(map.value!, e.data.lnglat)
    })
  }
}
const handleCoverInit = () => {
  if (isInit.value && map.value) {
    massmarks.value = new AMap.MassMarks(returnLocation.value, {
      style: getStyle()
    })
    massmarks.value.setMap(map.value)
    const firstReturn = returnLocation.value[0]
    const center = new AMap.LngLat(firstReturn.lnglat[0], firstReturn.lnglat[1])
    map.value.setCenter(center)
    infowindow.value = new AMap.InfoWindow({
      autoMove: true,
      offset: new AMap.Pixel(15, 0),
      isCustom: true
    })
    massmarks.value.on('click', handleMassMarksClick)
    circle.value = new AMap.Circle({
      center,
      radius: firstReturn.radius,
      fillColor: '#F3860A',
      fillOpacity: 0.1,
      strokeOpacity: 0
    })
    map.value?.add(circle.value)
    circle.value?.hide()
  }
}
const router = useRouter()
const showContactBike = (type: FeeRulesType) => {
  router.push({
    name: 'FeeRulesContactBike',
    query: {
      feeRule: type,
      storeId: route.query.storeId
    }
  })
}
const handleActivated = async () => {
  await getData()
  handleCoverInit()
}
onMounted(() => {
  init()
})
onActivated(() => {
  form.storeId = (route.query.storeId as string) || ''
})
useActivated(form, { form }, [{ key: 'storeId', path: 'form.storeId' }], handleActivated, [])
</script>

<template>
  <div class="xy-container">
    <div flex flex-col class="time-rent-configure__base">
      <span class="title">短租配置</span>
      <div flex>
        <div class="point point--danger" mr-10 />
        <span
          >强制还车配置:<span class="red">{{ dispatchFee }}元</span></span
        >
      </div>
      <div flex flex-col>
        <div flex>
          <div class="point point--success" mr-10 />
          <span>计费规则</span>
        </div>
        <div flex>
          <div class="timebased-info">
            <div class="timebased-info__title">
              <span>① 按时长计费</span>
              <span @click="showContactBike('TimeBased')">已关联车辆></span>
            </div>
            <div class="timebased-info__content">
              <div class="timebased-info__item" v-for="(item, index) in product" :key="index">
                <span class="text-[14px] text-[#000000]">{{ item.name }}</span>
                <span class="text-[12px] text-[#666666]">{{ item.productDescription }}</span>
              </div>
            </div>
          </div>
          <div class="tiered-info">
            <div class="tiered-info__title">
              <span>① 按阶梯计费</span>
              <span @click="showContactBike('Tiered')">已关联车辆></span>
            </div>
            <div class="tiered-info__content">
              <div class="tiered-info__item" v-for="(item, index) in feeRuleDetail" :key="index">
                <div class="tiered-info__top">
                  <span class="tiered-info__top__title">{{ item.title }}</span>
                  <span class="tiered-info__top__tip">({{ item.tips }})</span>
                </div>
                <div class="tiered-info__bottom">
                  <span class="tiered-info__bottom__cost">{{ item.cost }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div flex flex-col flex-1 class="time-rent-configure__map">
      <span mb-20>已采集还车点 ({{ returnLocation.length }}个)</span>
      <div ref="mapContainer" id="map-container" flex-1 />
    </div>
  </div>
</template>

<style scoped lang="scss">
.time-rent-configure__base {
  background: #fff;
  box-shadow: 0px 0px 20px 1px rgba(0, 0, 0, 0.05);
  border-radius: 5px 5px 5px 5px;
  padding: 20px;
}
.time-rent-configure__base > * {
  margin-bottom: 10px;
}
.time-rent-configure__base > span {
  font-family:
    Source Han Sans SC,
    Source Han Sans SC;
  font-weight: 500;
  font-size: 14px;
  color: #333333;
  line-height: 20px;
}
.time-rent-configure__base > .title {
  margin-bottom: 20px;
  font-family:
    Source Han Sans SC,
    Source Han Sans SC;
  font-size: 16px;
  color: #000000;
  line-height: 24px;
}
.point {
  width: 4px;
  height: 12px;
  border-radius: 2px 2px 2px 2px;
}
.point--danger {
  background-color: var(--xy-danger-color);
}
.point--success {
  background-color: var(--xy-success-color);
}
.point--warning {
  background-color: var(--xy-warning-color);
}
.timebased-info,
.tiered-info {
  background: #f5f5f5;
  border-radius: 10px 10px 10px 10px;
  padding: 10px;
  display: flex;
  flex-direction: column;
}
.timebased-info {
  margin-right: 15px;
  &__title {
    display: flex;
    justify-content: space-between;
    span:first-child {
      font-family:
        Source Han Sans SC,
        Source Han Sans SC;
      font-size: 14px;
      color: #333333;
      line-height: 20px;
    }
    span:last-child {
      font-family:
        Source Han Sans SC,
        Source Han Sans SC;
      font-size: 14px;
      color: #39bcb7;
      line-height: 20px;
    }
  }
  &__content {
    padding: 10px;
    display: flex;
    flex-direction: column;
  }
  &__item {
    background: #ffffff;
    border-radius: 10px 10px 10px 10px;
    line-height: 46px;
    padding: 0 10px;
    width: 100%;
    white-space: nowrap;
  }
  &__item + &__item {
    margin-top: 10px;
  }
}
.tiered-info {
  flex: 1;
  &__title {
    display: flex;
    justify-content: space-between;
    span:first-child {
      font-family:
        Source Han Sans SC,
        Source Han Sans SC;
      font-size: 14px;
      color: #333333;
      line-height: 20px;
    }
    span:last-child {
      font-family:
        Source Han Sans SC,
        Source Han Sans SC;
      font-size: 14px;
      color: #39bcb7;
      line-height: 20px;
    }
  }
  &__content {
    padding: 10px;
    display: grid;
    grid-template-rows: repeat(auto-fill, 1fr);
    grid-auto-flow: row;
    grid-template-columns: repeat(auto-fill, 150px);
    grid-auto-columns: 1fr;
  }
  &__item {
    display: flex;
    flex-direction: column;
  }
  &__top {
    --at-apply: flex flex-col items-center bg-white py-5 px-15;
    border: 1px solid #eeeeee;
    &__title {
      font-size: 14px;
      color: #333333;
      line-height: 20px;
      white-space: nowrap;
    }
    &__tip {
      font-size: 12px;
      color: #999999;
      line-height: 15px;
      white-space: nowrap;
    }
  }
  &__bottom {
    --at-apply: flex flex-col items-center leading-25 bg-white py-5;
    border: 1px solid #eeeeee;
    border-top: none;
    border-bottom: none;
    &__cost {
      font-size: 14px;
      color: #000000;
      white-space: nowrap;
    }
  }
  &__item + &__item {
    > div {
      border-left: none;
    }
  }
}
.red {
  color: #ff6d75;
}
.time-rent-configure__map {
  background: #fff;
  margin-top: 20px;
  padding: 20px;
  box-sizing: border-box;
}
:deep(.return-point-infowindow) {
  z-index: 200;
  position: relative;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
  border-radius: 5px 5px 5px 5px;
  padding: 10px;
  .return-point-infowindow__title {
    display: flex;
    align-items: center;
    white-space: nowrap;
    .return-point-infowindow__name {
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: 500;
      font-size: 16px;
      color: rgba(51, 51, 51, 0.99);
      line-height: 22px;
    }
    .return-point-infowindow__id-content {
      line-height: 19px;
      background: rgba(243, 134, 10, 0.1);
      border-radius: 2px 2px 2px 2px;
      padding: 1px 4px;
      display: inline-block;
      text-align: center;
      font-family:
        PingFang SC,
        PingFang SC;
      font-size: 12px;
      color: #f3860a;
      margin-left: 10px;
    }
  }
  .return-point-infowindow__address {
    font-family:
      PingFang SC,
      PingFang SC;
    font-size: 14px;
    color: rgba(102, 102, 102, 0.99);
    line-height: 19px;
    white-space: normal;
  }
}
</style>
